import logging

from coin.exchange.binance.kr_rest.native_private_client import (
    BinanceSyncQueryer,
    BinanceAsyncQueryer,
    binance_req_timestamp,
)


BINANCE_FUTURE_API_URL = 'dapi.binance.com'


class BinanceFuturesSyncQueryer(BinanceSyncQueryer):
  def __init__(self, key_file, *, api_host=None, timeout=10):
    super().__init__(key_file, api_host=api_host, timeout=timeout)
    self._api_host = "https://" + (api_host or BINANCE_FUTURE_API_URL)
    logging.info('[BinanceFuturesSyncQueryer]: using api_host %s', self._api_host)


class BinanceFuturesAsyncQueryer(BinanceAsyncQueryer):
  def __init__(self, key_file, *, api_host=None, timeout=10, max_connections=4):
    super().__init__(key_file, api_host=api_host, timeout=timeout, max_connections=max_connections)
    self._api_host = "https://" + (api_host or BINANCE_FUTURE_API_URL)
    logging.info('[BinanceFuturesAsyncQueryer]: using api_host %s', self._api_host)


class BinanceFuturesNativePrivateClient(object):
  def __init__(
      self,
      *,
      key_file,
      api_host=None,
      timeout=10,
      max_connections=8,
      recv_window=None,  # default to 5000
      use_async=False,
  ):
    if use_async:
      self._auth_queryer = BinanceFuturesAsyncQueryer(key_file,
                                                      api_host=api_host,
                                                      timeout=timeout,
                                                      max_connections=max_connections)
    else:
      self._auth_queryer = BinanceFuturesSyncQueryer(key_file, api_host=api_host, timeout=timeout)

    self._recv_window = recv_window

  def _query(self, method, path, params=None):
    return self._auth_queryer.query(method, path, params=params)

  def query_account(self):
    method = 'GET'
    path = '/dapi/v1/account'
    params = {
        'recvWindow': self._recv_window,
        'timestamp': binance_req_timestamp(),
    }
    update = self._query(method, path, params)
    return update

  def query_position_risk(self):
    method = 'GET'
    path = '/dapi/v1/positionRisk'
    params = {
        'recvWindow': self._recv_window,
        'timestamp': binance_req_timestamp(),
    }
    update = self._query(method, path, params)
    return update

  def query_userTrades(self, symbol):
    method = 'GET'
    path = '/dapi/v1/userTrades'
    params = {
        'symbol': symbol,
        'recvWindow': self._recv_window,
        'timestamp': binance_req_timestamp(),
    }
    update = self._query(method, path, params)
    return update
